package com.huan.project;

import org.apache.commons.io.FileUtils;
import org.json.JSONException;

import java.io.*;
import java.net.Socket;
import java.net.URL;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        //1.创建Socket，连接到服务器
        Socket socket = new Socket("localhost",10003);
        System.out.println("连接成功"+socket);
        try (
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                ){
            System.out.println(getMessageFromServer(reader));
//            String mess = "";
//            System.out.println("hello?");
//            while (reader.readLine()!=null){
//                mess += reader.readLine();
//                System.out.println("hei?");
//            }
//            System.out.println(mess+"111111111");
            System.out.println(socket.isClosed());
            Scanner scanner = new Scanner(System.in);
            while (!socket.isClosed()) {
                //客户端发送请求
                String message = scanner.next();
//                writer.write(message);
//                writer.newLine();
//                writer.flush();
                sendMessage(writer,message);

                // 读取服务器发送的消息
                System.out.println("getMessageFromServer(reader) = " + getMessageFromServer(reader));
                if ("5".equals(message)){
                    System.out.println("与服务器断开连接");
                    socket.close();
                    break;
                }
            }
//            while (!socket.isClosed()){
//                String operate = scanner.next();
//                sendMessage(outputStream,operate);
//                System.out.println(getMessageFromServer(inputStream));
//            }
        }
        //2.接受服务器消息
//        try (InputStream inputStream = socket.getInputStream()){
//            byte[] bytes = new byte[1024];
//            int length = -1;
//            System.out.println("客户端等待服务端的响应");
//            while((length=inputStream.read(bytes,0,bytes.length))!=-1){
//                String string = new String(bytes,0,length);
//                System.out.println("服务器的响应:\n"+string);
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        //3.发送请求
//        System.out.println(socket.isClosed());
//        Scanner scanner = new Scanner(System.in);
//        while (!socket.isClosed()){
//            String operate = scanner.next();
//            sendMessage(socket,operate);
//            System.out.println(getMessageFromServer(socket));
//        }
        //4.接收服务器响应
        //5.发送结束信号
    }
//    private static class ClientHandler implements Runnable {
//        private Socket s;
//
//        public ClientHandler(Socket socket) {
//            this.s = socket;
//        }
//
//        @Override
//        public void run() {
//            try {
//                Socket socket = this.s;//如果没有这个语句，则socket不能自动关闭
//                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//                while (true) {
//                    writer.write(response);
//                    writer.newLine();
//                    writer.flush();
//
//                    // 读取客户端发送的消息
//                    String clientMessage = reader.readLine();
//                    if (clientMessage == null) {
//                        break; // 客户端断开连接
//                    }
//                    System.out.println("Received message from client: " + clientMessage);
//                    // 根据收到的消息，处理业务逻辑
//
//
//                    String response = "Server: " + clientMessage.toUpperCase();
//                    writer.write(response);
//                    writer.newLine();
//                    writer.flush();
//
//                    System.out.println("Sent response to client: " + response);
//                }
//
//                // 关闭连接
//                socket.close();
//                System.out.println("Connection closed");
//            } catch (IOException | JSONException e) {
//                e.printStackTrace();
//            }
//        }
//    }
    //接收服务器响应
    private static String getMessageFromServer(BufferedReader reader) throws IOException {
        String message = "";
        String line = null;
        /**
         * 遇到的问题：
         * 在运行以下代码时，读到最后一行内容会阻塞住
         * while((line=reader.readLine())!=null){
         *     line = reader.readLine()+"\n";
         *             message += line;
         * }
         *
         * 解决：https://www.cnblogs.com/shisandao/p/13969019.html
         * 使用ready()方法判断是否还有数据没有读取
         * 但是需要注意：需要使用do-while循环来避免因为输入流一开始没有数据而导致整个循环被跳过
         */
        do {
            line = reader.readLine()+"\n";
            message += line;
//            System.out.println(line);
        } while (reader.ready());
//        System.out.println(message+"111111111");
        return message;
    }

    public static void sendMessage(BufferedWriter writer, String message) throws IOException {
        writer.write(message);
        writer.newLine();
        writer.flush();
    }

    //客户端 下载文件到指定位置
    public static void downloadFile(String fileUrl, String fileName) throws IOException {
        String imageUrl = fileUrl; // 图片的 URL
        String localPath = "C:/"+fileName; // 本地保存路径

        try (InputStream in = new URL(imageUrl).openStream()) {
            FileUtils.copyInputStreamToFile(in, new File(localPath));
            System.out.println("图片下载成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
